package com.qx.cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.Role;
import com.qx.cn.model.RoleMenu;
import com.qx.cn.model.UserRole;
import com.qx.cn.service.MenuButtonService;
import com.qx.cn.service.RoleGroupMappingService;
import com.qx.cn.service.RoleMenuService;
import com.qx.cn.service.RoleService;
import com.qx.cn.service.UserRoleService;
import com.qx.cn.tool.ReDupList;
import com.qx.cn.vo.RoleVO;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({@Result(name = "outlogin", location = "/admin!loseSession"), @Result(name = "getOutlogin", location = "/admin!otherlogin"),
    @Result(name = "roleList", location = "/WEB-INF/page/roleInfo/roleList.jsp")})
@Action(value = "role", interceptorRefs = {@InterceptorRef("loginedCheck")})
public class RoleAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -12085331768508649L;
    
    private int page;
    
    private int rows;
    
    private Long roleId;
    
    private String roleName;
    
    private String roleDesc;
    
    private Integer enabled;
    
    private String strBuffer;
    
    private String userId;
    
    private String orgCode;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleMenuService roleMenuService;
    
    @Autowired
    private MenuButtonService menuButtonService;
    
    @Autowired
    private RoleGroupMappingService roleGroupMappingService;
    
    public String getUserId()
    {
        return userId;
    }
    
    public void setUserId(String userId)
    {
        this.userId = userId;
    }
    
    public MenuButtonService getMenuButtonService()
    {
        return menuButtonService;
    }
    
    public void setMenuButtonService(MenuButtonService menuButtonService)
    {
        this.menuButtonService = menuButtonService;
    }
    
    public String roleListForm()
    {
        return "roleList";
    }
    
    public String queryRoleListByPage()
    {
        List results = roleService.queryRolesByPage(page, rows);
        JSONArray arrJson = new JSONArray();
        if (results.size() > 0)
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("roleId", (Integer)row[0]);
                json.put("roleName", (String)row[1]);
                json.put("enabled", (Integer)row[2]);
                json.put("roleDesc", (String)row[3]);
                String optMenuUrl = "<span style='color:#00C;cursor:hand;' onclick=giveRoleToMenu('" + (Integer)row[0] + "','【" + (String)row[1] + "】')>[设置菜单]</span>&nbsp;";
                
                json.put("optRoleUrl", optMenuUrl);
                arrJson.add(json);
            }
        }
        
        JSONObject object = new JSONObject();
        List<Role> roles = roleService.queryAllRoles();
        object.put("total", Integer.valueOf(roles.size()));
        object.put("rows", arrJson);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveRole()
        throws IOException
    {
        if (roleId != null)
        {
            Role reRole = roleService.loadRoleById(roleId);
            reRole.setRoleName(roleName);
            reRole.setEnabled(enabled);
            reRole.setRoleDesc(roleDesc);
            roleService.saveRole(reRole);
        }
        else
        {
            Role role = new Role();
            role.setRoleName(roleName);
            role.setEnabled(enabled);
            role.setRoleDesc(roleDesc);
            roleService.saveRole(role);
        }
        
        JSONObject object = new JSONObject();
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String deleteRole()
    {
        String roleId = String.valueOf(this.roleId);
        boolean flag1 = roleGroupMappingService.deleteRoleAtMapping(roleId);
        boolean flag2 = userRoleService.deleteUserRoles(roleId);
        boolean flag3 = roleMenuService.deleteRoleMenusById(roleId);
        boolean flag = roleService.deleteRole(this.roleId);
        
        JSONObject object = new JSONObject();
        if ((flag) && (flag1) && (flag2) && (flag3))
        {
            object.put("result", 1);
            object.put("errorMsg", "删除角色成功");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "删除角色失败");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loadRoleById()
    {
        JSONObject object = new JSONObject();
        Role role = roleService.loadRoleById(roleId);
        object.put("roleId", role.getRoleId());
        object.put("roleName", role.getRoleName());
        object.put("enabled", role.getEnabled());
        object.put("roleDesc", role.getRoleDesc());
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveUserToRole()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] userId = strBuffer.split(",");
        String roleId = String.valueOf(this.roleId);
        List<UserRole> userRoles = userRoleService.queryUserRolesById(orgCode, roleId);
        if (userRoles.size() > 0)
        {
            if (userRoleService.deleteUserRoles(orgCode, roleId))
            {
                for (int i = 0; i < userId.length; i++)
                {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(this.roleId);
                    userRole.setUserId(Long.valueOf(userId[i]));
                    userRole.setOrgCode(orgCode);
                    boolean flag1 = userRoleService.saveUserRole(userRole);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < userId.length; i++)
            {
                UserRole userRole = new UserRole();
                userRole.setRoleId(this.roleId);
                userRole.setUserId(Long.valueOf(userId[i]));
                userRole.setOrgCode(orgCode);
                boolean flag1 = userRoleService.saveUserRole(userRole);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveMenuToRole()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] menuCode = strBuffer.split(",");
        String roleId = String.valueOf(this.roleId);
        List<RoleMenu> roleMenus = roleMenuService.queryRoleMenusById(roleId);
        List<String> menuList;
        if (roleMenus.size() > 0)
        {
            List<RoleMenu> rms = roleMenuService.queryRoleMenusByIdAndBT(roleId);
            
            boolean flag2 = roleMenuService.deleteRoleMenusById(roleId);
            
            if (flag2)
            {
                List list = new ArrayList();
                for (int i = 0; i < menuCode.length; i++)
                {
                    list.add(menuCode[i]);
                    if (menuCode[i].length() != 4)
                    {
                        list.add(menuCode[i].substring(0, menuCode[i].length() - 3));
                    }
                }
                
                menuList = ReDupList.removeDuplicate(list);
                boolean flag1 = true;
                for (String mls : menuList)
                {
                    boolean addFlag = false;
                    String addMenuCode = "";
                    if (rms.size() > 0)
                    {
                        for (RoleMenu rm : rms)
                        {
                            if (mls.equals(rm.getMenuId()))
                            {
                                RoleMenu roleMenu = new RoleMenu();
                                roleMenu.setRoleId(roleId);
                                roleMenu.setMenuId(mls);
                                addMenuCode = rm.getMenuId();
                                if ((rm.getButtonIds() != null) && (rm.getTabIds() == null))
                                {
                                    roleMenu.setButtonIds(rm.getButtonIds());
                                }
                                else if ((rm.getButtonIds() == null) && (rm.getTabIds() != null))
                                {
                                    roleMenu.setTabIds(rm.getTabIds());
                                }
                                else if ((rm.getButtonIds() != null) && (rm.getTabIds() != null))
                                {
                                    roleMenu.setTabIds(rm.getTabIds());
                                    roleMenu.setButtonIds(rm.getButtonIds());
                                }
                                flag1 = roleMenuService.saveRoleMenu(roleMenu);
                                if (!flag1)
                                {
                                    flag = false;
                                }
                            }
                            else
                            {
                                addFlag = true;
                            }
                        }
                        
                        if ((addFlag) && (!addMenuCode.equals(mls)))
                        {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setRoleId(roleId);
                            roleMenu.setMenuId(mls);
                            flag1 = roleMenuService.saveRoleMenu(roleMenu);
                            if (!flag1)
                            {
                                flag = false;
                            }
                        }
                    }
                    else
                    {
                        RoleMenu roleMenu = new RoleMenu();
                        roleMenu.setRoleId(roleId);
                        roleMenu.setMenuId(mls);
                        boolean flag3 = roleMenuService.saveRoleMenu(roleMenu);
                        if (!flag3)
                        {
                            flag = false;
                        }
                    }
                }
            }
        }
        else
        {
            List list = new ArrayList();
            for (int i = 0; i < menuCode.length; i++)
            {
                list.add(menuCode[i]);
                if (menuCode[i].length() != 4)
                {
                    list.add(menuCode[i].substring(0, menuCode[i].length() - 3));
                }
            }
            
            menuList = ReDupList.removeDuplicate(list);
            for (String mls : menuList)
            {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(mls);
                boolean flag1 = roleMenuService.saveRoleMenu(roleMenu);
                if (!flag1)
                {
                    flag = false;
                }
            }
            
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色菜单成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色菜单失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String queryAllRolesToUser()
    {
        List<Role> roles = roleService.queryAllRoles();
        List<UserRole> userRoles = userRoleService.queryRolesByUserId(Long.valueOf(userId));
        List roleVOs = new ArrayList();
        for (Role role : roles)
        {
            int sign = 0;
            RoleVO roleVO = new RoleVO();
            for (UserRole ur : userRoles)
            {
                if (role.getRoleId().equals(ur.getRoleId()))
                {
                    sign = 1;
                }
            }
            
            roleVO.setRoleId(role.getRoleId());
            roleVO.setRoleName(role.getRoleName());
            roleVO.setRoleDesc(role.getRoleDesc());
            roleVO.setEnabled(role.getEnabled());
            roleVO.setSign(Integer.valueOf(sign));
            roleVOs.add(roleVO);
        }
        JSONObject object = new JSONObject();
        object.put("datas", roleVOs);
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveTabsMenuToRole()
    {
        JSONObject object = new JSONObject();
        String roleId = String.valueOf(this.roleId);
        roleMenuService.updateRoleTabsByRoleId(roleId);
        if (!"".equals(strBuffer))
        {
            String[] menuTabs = strBuffer.split("#");
            
            List list = new ArrayList();
            for (int i = 0; i < menuTabs.length; i++)
            {
                String[] mbs = menuTabs[i].split(",");
                list.add(mbs[0]);
            }
            
            List<String> list2 = ReDupList.removeDuplicate(list);
            
            for (String ls : list2)
            {
                StringBuffer sBuffer = new StringBuffer();
                for (int i = 0; i < menuTabs.length; i++)
                {
                    String[] mbs = menuTabs[i].split(",");
                    if (mbs[0].equals(ls))
                    {
                        sBuffer.append(mbs[1]).append(",");
                    }
                }
                
                roleMenuService.updateRoleTabsByMenuCode(roleId, ls, sBuffer.toString());
            }
        }
        
        object.put("result", 1);
        object.put("errorMsg", "设置角色选项卡成功!");
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveButsMenuToRole()
    {
        JSONObject object = new JSONObject();
        String roleId = String.valueOf(this.roleId);
        roleMenuService.updateRoleButsByRoleId(roleId);
        if (!"".equals(strBuffer))
        {
            String[] menuButs = strBuffer.split("#");
            
            List list = new ArrayList();
            for (int i = 0; i < menuButs.length; i++)
            {
                String[] mbs = menuButs[i].split(",");
                list.add(mbs[0]);
            }
            
            List<String> list2 = ReDupList.removeDuplicate(list);
            
            for (String ls : list2)
            {
                StringBuffer sBuffer = new StringBuffer();
                for (int i = 0; i < menuButs.length; i++)
                {
                    String[] mbs = menuButs[i].split(",");
                    if (mbs[0].equals(ls))
                    {
                        sBuffer.append(mbs[1]).append(",");
                    }
                }
                
                roleMenuService.updateRoleButsByMenuCode(roleId, ls, sBuffer.toString());
            }
        }
        
        object.put("result", 1);
        object.put("errorMsg", "设置角色按钮成功!");
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveRoleToUser()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] roleId = strBuffer.split(",");
        List userRoles = userRoleService.queryRolesByUserId(Long.valueOf(userId));
        if (userRoles.size() > 0)
        {
            boolean flag2 = userRoleService.deleteRolesUser(Long.valueOf(userId));
            if (flag2)
            {
                for (int i = 0; i < roleId.length; i++)
                {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(Long.valueOf(roleId[i]));
                    userRole.setUserId(Long.valueOf(userId));
                    userRole.setOrgCode(orgCode);
                    boolean flag1 = userRoleService.saveUserRole(userRole);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < roleId.length; i++)
            {
                UserRole userRole = new UserRole();
                userRole.setRoleId(Long.valueOf(roleId[i]));
                userRole.setUserId(Long.valueOf(userId));
                userRole.setOrgCode(orgCode);
                boolean flag1 = userRoleService.saveUserRole(userRole);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public int getPage()
    {
        return page;
    }
    
    public void setPage(int page)
    {
        this.page = page;
    }
    
    public int getRows()
    {
        return rows;
    }
    
    public void setRows(int rows)
    {
        this.rows = rows;
    }
    
    public String getRoleName()
    {
        return roleName;
    }
    
    public void setRoleName(String roleName)
    {
        this.roleName = roleName;
    }
    
    public String getRoleDesc()
    {
        return roleDesc;
    }
    
    public void setRoleDesc(String roleDesc)
    {
        this.roleDesc = roleDesc;
    }
    
    public Integer getEnabled()
    {
        return enabled;
    }
    
    public void setEnabled(Integer enabled)
    {
        this.enabled = enabled;
    }
    
    public String getStrBuffer()
    {
        return strBuffer;
    }
    
    public void setStrBuffer(String strBuffer)
    {
        this.strBuffer = strBuffer;
    }
    
    public String getOrgCode()
    {
        return orgCode;
    }
    
    public void setOrgCode(String orgCode)
    {
        this.orgCode = orgCode;
    }
    
    public Long getRoleId()
    {
        return roleId;
    }
    
    public void setRoleId(Long roleId)
    {
        this.roleId = roleId;
    }
}